package top.magicpotato.app;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private static final Path CONFIG_PATH = Paths.get(System.getProperty("user.dir"), "config.properties");

    public static void main(String[] args) throws Exception {
        // 校验配置文件
        checkConfigFile();
        // 开启ftp
        statFtp();

        // 主线程等待
        synchronized (Application.class) {
            Application.class.wait();
        }
    }

    private static void checkConfigFile() throws IOException {
        if (!CONFIG_PATH.toFile().exists()) {
            logger.info("{} 不存在，初始化新的配置文件", CONFIG_PATH);
            InputStream resourceAsStream = Application.class.getResourceAsStream("/config.properties");
            if (resourceAsStream == null) {
                return;
            }
            Files.write(CONFIG_PATH, resourceAsStream.readAllBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        }
    }

    private static void statFtp() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(2121);

        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory pum = new PropertiesUserManagerFactory();
        pum.setFile(CONFIG_PATH.toFile());
        pum.setPasswordEncryptor(new ClearTextPasswordEncryptor());
        serverFactory.setUserManager(pum.createUserManager());
        FtpServer server = serverFactory.createServer();
        server.start();
        // 成功提示
        logger.info("ftp启动成功，访问地址：{}:{}", Inet4Address.getLocalHost().getHostAddress(), factory.getPort());

    }
}
